<?php

// 创建项目
// POST project.create

namespace app\api\resource\project;
use think\Db;
use think\Loader;
use think\Session;

class Create
{
    // 方法
    public $_method = ['POST'];
    // 前置
    public $_pre    = ['login','isCyz'];
    // 描述
    public $_description = '创建项目';
    // 参数
    public $_param  = [
        'title'        => '项目名称',
        'words'        => '一句话介绍',
        'logo'         => '项目图标',
        'stage'        => '所处阶段',
        'round'        => '融资轮次',
        'industry'     => '所属行业',
        'city'         => '所在城市',
        'money'        => '融资金额(万)',
        'introduction' => '项目简介',
        'atlas'        => '项目图集,JsonArray',
    ];
    // 返回
    public $_return = [
        201 => '创建成功',
        400 => '每个用户只能创建3个项目',
        422 => '请求参数不合法',
        500 => '服务器错误',
    ];

    public function run(&$request)
    {
        $params['member_id']    = Session::get('member.id');
        $params['title']        = $request->post('title/s','','trim');
        $params['words']        = $request->post('words/s','','trim');
        $params['logo']         = $request->post('logo/s','','trim');
        $params['stage']        = $request->post('stage/s','','trim');
        $params['round']        = $request->post('round/s','','trim');
        $params['industry']     = $request->post('industry/s','','trim');
        $params['city']         = $request->post('city/s','','trim');
        $params['money']        = $request->post('money/s','','trim');
        $params['introduction'] = $request->post('introduction/s','','trim');
        $params['atlas']        = $request->post('atlas/s','','trim');

        $validate = Loader::validate('Project');
        if ( !$validate->scene('create')->check($params) ) {
            $errMsg = $validate->getError();
            return [422,$errMsg];
        }

        $num = Db::name('project')->where('member_id',$params['member_id'])->where('delete_time',0)->count();
        if ($num >= 3) return [400,'每个用户只能创建3个项目'];

        $params['create_time'] = time();
        $id = Db::name('project')->insertGetId($params);

        if ($id > 0) {
            // 初始化运营数据表
            $this->_init_project_data($id, $params['member_id']);
            
            return [ 201,[] ];
        } else {
            return 500;
        }
    }

    // 初始化运营数据表
    private function _init_project_data($projectId, $memberId)
    {
        $data['project_id'] = $projectId;
        $data['member_id']  = $memberId;
        $num = Db::name('project_data')->insert($data);
        return ($num > 0);
    }
}